import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import NProgress from 'nprogress'
import { regMsgEvent, EVENT_TYPE } from '@utility/eventBus.js'
import { debounce, parseJsonStr } from '@utility/utility'
import enterprise from './modules/enterprise.js' // 企业名录、企业维护
import judgAlgorithm from './modules/judgAlgorithm.js' // 判定算法管理
import judgRule from './modules/judgRule.js' // 判定规则管理
import judgMonitor from './modules/judgMonitor.js' // 企业判定监测
import judgApproval from './modules/judgApproval.js' // 企业判定审批
import helpPolicy from './modules/helpPolicy.js' // 企业判定审批
import optimizationPlan from './modules/optimizationPlan.js' // 帮扶政策优化方案

NProgress.configure({ showSpinner: false, easing: 'ease-in-out' })

Vue.use(VueRouter)

const perPages = []

const routerPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return routerPush.call(this, location, onResolve, onReject)
  return routerPush.call(this, location).catch(error => error)
}
// import pdf from '@views/home/pdf.vue'

/**
 * meta:属性说明
 * title：面包屑显示内容
 * breadcrumbHide：是否不添加到面包屑中， 如果设置为true， 则不会在breadcrumb面包屑中显示(默认 false)
 * keepAlive：是否缓存
 * deepth：页面层级，用于是否更新缓存，由大到小不更新，小到大更新，
 *
 */

const routes = [
  {
    // main layout 全屏根路由
    path: '/',
    name: 'mainLayout',
    component: () => import('@layouts/main.vue'),
    redirect: '/home',
    children: [
      {
        // header layout 提供 通用 header 组件
        path: '/layout-header',
        name: 'layoutHeader',
        component: () => import('@layouts/header.vue'),
        children: [
          // 含有侧边栏的布局页面
          {
            path: '/layout-slide',
            name: 'layoutSlide',
            component: () => import('@layouts/slide.vue'),
            children: [
              // 首页
              {
                path: '/home',
                name: 'BBCS_HOME',
                component: () => import('@views/homePage/index.vue'),
                meta: {
                  title: '首页',
                  deepth: 1,
                },
              },
              ...enterprise,
              ...judgRule,
              ...judgAlgorithm,
              ...judgMonitor,
              ...judgApproval,
              ...helpPolicy,
              ...optimizationPlan,
            ],
          },
          // 无权限
          {
            path: '/403',
            name: 'NO_ACCESS',
            component: () => import('@views/auth/403.vue'),
          },
          { path: '/404', name: 'pageNotFound', component: () => import('@views/auth/404.vue') },
        ],
      },
      {
        path: '/pdf',
        name: 'PDF_PAGE',
        component: () => import('@views/pdfViewer/index.vue'),
      },
      {
        path: '/',
        redirect: '/login',
      },
      {
        path: '/login',
        name: 'LOGIN',
        component: () => import('@views/auth/Login.vue'),
      },
    ],
  },
  { path: '*', redirect: '/404' },
]
// 开发环境下，将page中的 router 定义 导入到根router中方便测试

// console.log('%c⧭', 'color: #99adcc', routes)
const router = new VueRouter({
  // base: import.meta.env.BASE_URL,
  routes: routes,
})

router.beforeEach(async (to, from, next) => {
  // 规避重复push路由问题，会引起replace自身时不起作用
  if (to.name) NProgress.start()
  if (to.fullPath === from.fullPath) {
    return false
  } else {
    // 判断设置权限的页面
    if (perPages.includes(to.name)) {
      // 判断用户是否有权限进入该页面
      const codesStr = localStorage.getItem('EFF_BBCS_PERMISSION_CODES')
      if (codesStr) {
        const menuCodes = parseJsonStr(codesStr)
        if (menuCodes && menuCodes.includes(to.name)) {
          next()
          NProgress.done()
        } else {
          next({ path: '/403' })
          NProgress.done()
        }
      } else {
        next()
        NProgress.done()
      }
    } else {
      next()
      NProgress.done()
    }
  }
  // 获取用户信息
  if (to.name !== 'LOGIN') {
    await store.dispatch('user/setUserInfos')
  }
})

router.afterEach((to, from) => {
  const cachedPages = store.getters.cachedPages
  const routerPages = JSON.parse(sessionStorage.getItem('routerPages')) || []
  if (routerPages.length > 0 && !routerPages.includes(to.name)) {
    routerPages.push(to.name)
    sessionStorage.setItem('routerPages', JSON.stringify(routerPages))
  }
  // home 页面 置空缓存页面
  if (to.name === 'home') {
    store.commit('setCachedPages', [])
    return
  }
  if (to.meta.keepAlive) {
    if (!cachedPages.includes(to.name)) {
      cachedPages.push(to.name)
      store.commit('setCachedPages', cachedPages)
    }
  }
  // 如果 要 form(离开) 的页面是 keepAlive缓存的，
  // 再根据 deepth 来判断是前进还是后退
  // 如果是后退
  if (from && cachedPages.includes(from.name)) {
    if (!from.meta.keepAlive || to.meta.deepth < from.meta.deepth) {
      const fromPageIdx = cachedPages.indexOf(from.name)
      cachedPages.splice(fromPageIdx, 1)
      store.commit('setCachedPages', cachedPages)
    }
  }
})

regMsgEvent(
  EVENT_TYPE.goLogin,
  debounce(() => {
    // 规避短时间内重复调用问题
    router.replace({
      name: 'LOGIN',
    })
  }, 2000)
)

export default router
